package engine;

import java.util.HashMap;

import engine.game.Avg2dGame;
import engine.game.BaseGame;
import engine.game.BasePanel;
import engine.loader.ConfigFileLoader;

public class Engine {
	public static final String RELEASE = "1";
	public static final String SERIAL = "1";
	public static final String NAME = "Vintage Engine";
	public static final String AUTHOR = "I-Fan Chen";

	private static Engine instance = null;

	private boolean initialized = false;
	private HashMap<String, String> config;

	private Logger logger;
	private BaseGame game;
	private BasePanel mainPanel;

	public static Engine getInstance() {
		if (instance == null) {
			instance = new Engine();
		}
		
		return instance;
	}

	private Engine() {
		logger = Logger.getInstance();
	}

	public void initializeConfiguration() {
		prepareConfiguration();
		
		ConfigFileLoader configFileLoader = new ConfigFileLoader(this, "config.cfg");
		configFileLoader.parse();
		
		postInitialization();
		initialized = true;
	}

	private void prepareConfiguration() {
		config = new HashMap<String, String>();
		config.put("window_width", String.valueOf(BasePanel.DEFAULT_WIDTH));
		config.put("window_height", String.valueOf(BasePanel.DEFAULT_HEIGHT));
		config.put("game_type", String.valueOf(BaseGame.TYPE_UNSUPPORTED));
		config.put("fps", String.valueOf(BaseGame.DEFAULT_FPS));
	}

	private void postInitialization() {
		int game_type = Util.parseInt(config.get("game_type"));
		
		switch (game_type) {
		case BaseGame.TYPE_AVG_2D:
			game = new Avg2dGame(Util.parseInt(config.get("fps")));
			break;
		default:
			logger.out(Logger.ERROR, "Game type unsupported.");
			logger.out(Logger.ERROR, "Engine stopped.");
			System.exit(1);
		}
	}

	public void initializeGraphics() {
		if (!initialized) {
			logger.out(Logger.ERROR, "Engine has not been initialized.");
			logger.out(Logger.ERROR, "Engine stopped.");
			System.exit(1);
			return;
		}
		
		mainPanel = new BasePanel(this);
		mainPanel.setGame(game);
	}

	public BasePanel getMainPanel() {return mainPanel;}

	public void setConfig(String key, String value) {
		if (config.containsKey(key)) {
			config.put(key, value);
			logger.out(Logger.DEV, key + ": " + value);
		}
	}

	public String getConfig(String key) {
		return config.get(key) == null ? "" : config.get(key);
	}

	public void setLogLevel(int logLevel) {
		logger.setLogLevel(logLevel);
	}

}